{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "11d1d65e4a450680",
   "metadata": {},
   "source": [
    "# Few-shot examples for chat models\n",
    "> This notebook covers how to use few-shot examples in chat models. There does not appear to be solid consensus on how best to do few-shot prompting, and the optimal prompt compilation will likely vary by model. Because of this, we provide few-shot prompt templates like the FewShotChatMessagePromptTemplate as a flexible starting point, and you can modify or replace them as you see fit.<br>\n",
    "> 本笔记本介绍了如何在聊天模型中使用少样本示例。对于如何最好地进行小样本提示，似乎没有达成坚实的共识，最佳提示编译可能因模型而异。因此，我们提供了像 FewShotChatMessagePromptTemplate 这样的小样本提示模板作为灵活的起点，您可以根据需要修改或替换它们。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b971506aa8298e24",
   "metadata": {},
   "source": [
    "## Fixed Examples\n",
    "> The most basic (and common) few-shot prompting technique is to use a fixed prompt example. This way you can select a chain, evaluate it, and avoid worrying about additional moving parts in production.<br>\n",
    "> 最基本（也是最常见的）小样本提示技术是使用固定提示示例。通过这种方式，您可以选择链条，对其进行评估，并避免担心生产中的其他移动部件。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "initial_id",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-17T23:39:37.750898Z",
     "start_time": "2024-07-17T23:39:37.204763Z"
    },
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Human: 2+2\n",
      "AI: 4\n",
      "Human: 2+3\n",
      "AI: 5\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.prompts import (\n",
    "    ChatPromptTemplate,\n",
    "    FewShotChatMessagePromptTemplate,\n",
    ")\n",
    "\n",
    "examples = [\n",
    "    {\"input\": \"2+2\", \"output\": \"4\"},\n",
    "    {\"input\": \"2+3\", \"output\": \"5\"},\n",
    "]\n",
    "\n",
    "# This is a prompt template used to format each individual example.\n",
    "example_prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"human\", \"{input}\"),\n",
    "        (\"ai\", \"{output}\"),\n",
    "    ]\n",
    ")\n",
    "few_shot_prompt = FewShotChatMessagePromptTemplate(\n",
    "    examples=examples,\n",
    "    example_prompt=example_prompt,\n",
    ")\n",
    "\n",
    "print(few_shot_prompt.format())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "781ef0dfe1c06dde",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-17T23:39:45.933909Z",
     "start_time": "2024-07-17T23:39:45.928889Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "System: You are a wondrous wizard of math.\n",
      "Human: 2+2\n",
      "AI: 4\n",
      "Human: 2+3\n",
      "AI: 5\n",
      "Human: What's the square of a triangle?\n"
     ]
    }
   ],
   "source": [
    "final_prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"You are a wondrous wizard of math.\"),\n",
    "        few_shot_prompt,\n",
    "        (\"human\", \"{input}\"),\n",
    "    ]\n",
    ")\n",
    "print(final_prompt.format(input=\"What's the square of a triangle?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1a69a5b20e498f82",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-18T00:33:01.147226Z",
     "start_time": "2024-07-18T00:32:57.545987Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\nAI: A triangle does not have a square, as it is a two-dimensional shape and a square is a three-dimensional shape. Do you perhaps mean the area of a triangle? In general, the area of a triangle can be found by multiplying the base by the height and then dividing by two (A = bh/2).'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import OpenAI\n",
    "\n",
    "chain = final_prompt | OpenAI(temperature=0.0)\n",
    "\n",
    "chain.invoke({\"input\": \"What's the square of a triangle?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f3a436ae54b659eb",
   "metadata": {},
   "source": [
    "## Dynamic few-shot prompting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "20ba591c9ccf4026",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'input': 'What did the cow say to the moon?', 'output': 'nothing at all'},\n",
       " {'input': '2+2', 'output': '4'}]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_chroma import Chroma\n",
    "from langchain_core.example_selectors import SemanticSimilarityExampleSelector\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "\n",
    "examples = [\n",
    "    {\"input\": \"2+2\", \"output\": \"4\"},\n",
    "    {\"input\": \"2+3\", \"output\": \"5\"},\n",
    "    {\"input\": \"2+4\", \"output\": \"6\"},\n",
    "    {\"input\": \"What did the cow say to the moon?\", \"output\": \"nothing at all\"},\n",
    "    {\n",
    "        \"input\": \"Write me a poem about the moon\",\n",
    "        \"output\": \"One for the moon, and one for me, who are we to talk about the moon?\",\n",
    "    },\n",
    "]\n",
    "\n",
    "to_vectorize = [\" \".join(example.values()) for example in examples]\n",
    "embeddings = OpenAIEmbeddings(model=\"text-embedding-3-small\")\n",
    "vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)\n",
    "\n",
    "example_selector = SemanticSimilarityExampleSelector(\n",
    "    vectorstore=vectorstore,\n",
    "    k=2,\n",
    ")\n",
    "\n",
    "# The prompt template will load examples by passing the input do the `select_examples` method\n",
    "example_selector.select_examples({\"input\": \"horse\"})\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "75c919a7f928a8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Human: 2+3\n",
      "AI: 5\n",
      "Human: 2+2\n",
      "AI: 4\n"
     ]
    }
   ],
   "source": [
    "from langchain_core.prompts import (\n",
    "    ChatPromptTemplate,\n",
    "    FewShotChatMessagePromptTemplate,\n",
    ")\n",
    "\n",
    "# Define the few-shot prompt.\n",
    "few_shot_prompt = FewShotChatMessagePromptTemplate(\n",
    "    # The input variables select the values to pass to the example_selector\n",
    "    input_variables=[\"input\"],\n",
    "    example_selector=example_selector,\n",
    "    # Define how each example will be formatted.\n",
    "    # In this case, each example will become 2 messages:\n",
    "    # 1 human, and 1 AI\n",
    "    example_prompt=ChatPromptTemplate.from_messages(\n",
    "        [(\"human\", \"{input}\"), (\"ai\", \"{output}\")]\n",
    "    ),\n",
    ")\n",
    "print(few_shot_prompt.format(input=\"What's 3+3?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "fe013d592d84718f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Human: 2+3\n",
      "AI: 5\n",
      "Human: 2+2\n",
      "AI: 4\n"
     ]
    }
   ],
   "source": [
    "final_prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"You are a wondrous wizard of math.\"),\n",
    "        few_shot_prompt,\n",
    "        (\"human\", \"{input}\"),\n",
    "    ]\n",
    ")\n",
    "print(few_shot_prompt.format(input=\"What's 3+3?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9e3530c5ade8fc6e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\nAI: 6'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import OpenAI\n",
    "\n",
    "chain = final_prompt | OpenAI(temperature=0.0)\n",
    "\n",
    "chain.invoke({\"input\": \"What's 3+3?\"})"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
